//
//  HRMessageRootViewController.m
//  Hear
//
//  Created by mac on 2017/5/20.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRMessageRootViewController.h"
#import "HRMessageRootSystemCell.h"
#import "HRDynamicMessageViewController.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "HRFMDBDynamicNotifacationTool.h"
#import "HRFollowListViewController.h"
#import "HRCircleOfFirendsViewController.h"
#import "YBPopupMenu.h"
#import "HRSearchFirendsViewController.h"

#import "HRFollowDynamicViewController.h"

@interface HRMessageRootViewController ()<DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,YBPopupMenuDelegate>
@property(nonatomic, strong)NSArray *sectionArray;
@property(nonatomic, strong)NSArray *sectionImageArray;

@property(nonatomic, assign)NSUInteger firendsUnreadCount;
@property(nonatomic, assign)NSUInteger circleUnreadCount;
@property(nonatomic, assign)NSUInteger hearVoiceUnreadCount;

/** 通知数量 */
@property (nonatomic, assign) NSUInteger noticeUnreadCount;

@end

@implementation HRMessageRootViewController

#pragma mark - Get and Set

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"消息";
    self.view.backgroundColor = [UIColor whiteColor];

    // 老版本
//    self.sectionArray = @[@"好友",@"点滴",@"留声机"];
//
//    self.sectionImageArray = @[@"消息_好友",@"朋友圈",@"消息-留声机"];

    // 新版本
    self.sectionArray = @[@"关注",@"点滴",@"通知"];
    self.sectionImageArray = @[@"消息_好友",@"通讯_点滴",@"通讯_通知"];
    
    [self setupView];
    
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];

    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newMessageNotifi) name:@"newMesageNotifi" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newFirendsNotifi) name:@"newFirendsNotifi" object:nil];
}

- (void)setupView{

    UIButton *addButton = [UIButton buttonWithType:0];
    [addButton setImage:[UIImage imageNamed:@"加号"] forState:0];
    addButton.size = CGSizeMake(30, 30);
    [addButton addTarget:self action:@selector(addButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"消息提示灰色"];
}
- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state{
    NSString *text = nil;
    UIFont *font = nil;
    UIColor *textColor = nil;
    text = @"去趣聊看看吧！";
    font = CustomUIFont(16);
    textColor = MainColor;
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    if (font) [attributes setObject:font forKey:NSFontAttributeName];
    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}
#pragma mark - DZNEmptyDataSetDelegate Methods

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    self.tabBarController.selectedIndex = 2;
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0){
        return self.sectionArray.count;
    }else{
        return self.dataArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 老版本
//    if (indexPath.section == 0){
//        HRMessageRootSystemCell *cell = [HRMessageRootSystemCell cellWithTableView:tableView];
//        cell.iconImageView.image = [UIImage imageNamed:self.sectionImageArray[indexPath.row]];
//        cell.typeLabel.text = self.sectionArray[indexPath.row];
//        if (indexPath.row == 0){
//            cell.unreadCount = self.firendsUnreadCount;
//        }else if (indexPath.row == 1){
//            cell.unreadCount = self.circleUnreadCount;
//        }else if (indexPath.row == 2){
//            cell.unreadCount = self.hearVoiceUnreadCount;
//        }
//        return cell;
//    }
    
    // 新版本
    if (indexPath.section == 0){
        HRMessageRootSystemCell *cell = [HRMessageRootSystemCell cellWithTableView:tableView];
        cell.iconImageView.image = [UIImage imageNamed:self.sectionImageArray[indexPath.row]];
        cell.typeLabel.text = self.sectionArray[indexPath.row];
        if (indexPath.row == 2){
            cell.unreadCount = self.noticeUnreadCount;
        }
        return cell;
    }
    
    NSString *CellIdentifier = [EaseConversationCell cellIdentifierWithModel:nil];
    EaseConversationCell *cell = (EaseConversationCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    [tableView setSeparatorColor:CustomColor(240, 240, 240, 1)];
    // Configure the cell...
    if (cell == nil) {
        cell = [[EaseConversationCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
        UILabel *lineLabel = [UILabel new];
        lineLabel.backgroundColor = CustomColor(240, 240, 240, 1);
        [cell  addSubview:lineLabel];
        lineLabel.frame = CGRectMake(70, 59, kFullWidth-70, 1);
    }
    
    if (indexPath.section == 0){
        EaseConversationModel *model = [EaseConversationModel new];
        model.avatarImage = [UIImage imageNamed:self.sectionImageArray[indexPath.row]];
        model.title = self.sectionArray[indexPath.row];
        cell.model = model;
        return cell;
    }
    
    if ([self.dataArray count] <= indexPath.row) {
        return cell;
    }
    
    id<IConversationModel> model = [self.dataArray objectAtIndex:indexPath.row];
    NSDictionary *dcit = model.conversation.latestMessage.ext;

    if (dcit[@"soundCard"]){
        model.avatarURLPath = dcit[@"UserPictureName"];
        model.title = dcit[@"nickName"];
        if (model.conversation.latestMessage.direction == EMMessageDirectionSend){
            cell.detailLabel.text =  @"你打了一个招呼";
        }else{
            cell.detailLabel.text =  @"你收到了一个招呼";
        }
        if ([model.conversation.conversationId isEqualToString:@"admin"]){
            model.title = @"hearer君";
            model.avatarURLPath = ADMINICON;
            cell.detailLabel.attributedText =  [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:[self _latestMessageTitleForConversationModel:model] textFont:cell.detailLabel.font];
        }
        cell.model = model;
        
        return cell;
    }
    
    if (model.conversation.latestMessage.direction == EMMessageDirectionSend){
        NSDictionary *dict = model.conversation.latestMessage.ext;
        model.title = model.conversation.latestMessage.ext[@"otherNickName"];
        model.avatarURLPath = model.conversation.latestMessage.ext[@"otherIcon"];
    }else{
        model.title = model.conversation.latestMessage.ext[@"nickName"];
        model.avatarURLPath = model.conversation.latestMessage.ext[@"icon"];
    }
    
    cell.model = model;
    
    if (self.dataSource && [self.dataSource respondsToSelector:@selector(conversationListViewController:latestMessageTimeForConversationModel:)]){
        NSMutableAttributedString *attributedText = [[self.dataSource conversationListViewController:self latestMessageTitleForConversationModel:model] mutableCopy];
        [attributedText addAttributes:@{NSFontAttributeName : cell.detailLabel.font} range:NSMakeRange(0, attributedText.length)];
        cell.detailLabel.attributedText =  attributedText;
    }else{
        cell.detailLabel.attributedText =  [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:[self _latestMessageTitleForConversationModel:model] textFont:cell.detailLabel.font];
    }

    if (self.dataSource && [self.dataSource respondsToSelector:@selector(conversationListViewController:latestMessageTimeForConversationModel:)]){
        cell.timeLabel.text = [self.dataSource conversationListViewController:self latestMessageTimeForConversationModel:model];
    }else{
        cell.timeLabel.text = [self _latestMessageTimeForConversationModel:model];
    }
    return cell;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (indexPath.section == 1){
            EaseConversationModel *model = [self.dataArray objectAtIndex:indexPath.row];
            [[EMClient sharedClient].chatManager deleteConversation:model.conversation.conversationId isDeleteMessages:YES completion:nil];
            [self.dataArray removeObjectAtIndex:indexPath.row];
            [self.tableView deleteRow:indexPath.row inSection:1 withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView reloadData];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTabItemBageCountNotifi" object:nil];

        }
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0){
        return NO;
    }else{
        return YES;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0){
        // 老版本
//        if (indexPath.row == 0){
//            [MobClick event:@"Hearer7"];
//            HRFollowListViewController *VC = [HRFollowListViewController new];
//            VC.followType = MutualFollowType;
//            [self.navigationController pushViewController:VC animated:YES];
//        }else if (indexPath.row == 1){
//            HRDynamicMessageViewController *VC = [HRDynamicMessageViewController new];
//            VC.title = @"点滴推送";
//            VC.pushTypeArray = @[@"1",@"2",@"5"];
//            [self.navigationController pushViewController:VC animated:YES];
//        } else {
////            [MobClick event:@"Hearer6"];
//            HRDynamicMessageViewController *VC = [HRDynamicMessageViewController new];
//            VC.title = @"留声机推送";
//            VC.pushTypeArray = @[@"9",@"12"];
//            [self.navigationController pushViewController:VC animated:YES];
//        }
        
        // 新版本
        if (indexPath.row == 0){
            // 关注
            HRFollowListViewController *VC = [HRFollowListViewController new];
            VC.followType = MyFollowType;
            [self.navigationController pushViewController:VC animated:YES];
        }else if (indexPath.row == 1){
            // 广场
            HRFollowDynamicViewController *vc = [HRFollowDynamicViewController new];
            [self.navigationController pushViewController:vc animated:YES];
        } else {
            // 通知
            HRDynamicMessageViewController *VC = [HRDynamicMessageViewController new];
            VC.title = @"通知";
            VC.pushTypeArray = @[@"1",@"2",@"5",@"9",@"12",@"13",@"14"];
            [self.navigationController pushViewController:VC animated:YES];
        }

    } else {
        if (self.delegate && [self.delegate respondsToSelector:@selector(conversationListViewController:didSelectConversationModel:)]) {
            EaseConversationModel *model = [self.dataArray objectAtIndex:indexPath.row];
            [self.delegate conversationListViewController:self didSelectConversationModel:model];
        } else {
            EaseConversationModel *model = [self.dataArray objectAtIndex:indexPath.row];
            EaseMessageViewController *viewController = [[EaseMessageViewController alloc] initWithConversationChatter:model.conversation.conversationId conversationType:model.conversation.type];
            
            NSString *otherNickName =@"";
            NSString *otherIcon =@"";
            NSString *otherIconColor =@"";
            
            NSDictionary *dict = model.conversation.latestMessage.ext;

            if (model.conversation.latestMessage.direction == EMMessageDirectionSend){
                otherNickName = model.conversation.latestMessage.ext[@"otherNickName"];
                otherIcon = model.conversation.latestMessage.ext[@"otherIcon"];
                otherIconColor = model.conversation.latestMessage.ext[@"otherIconColor"];
            }else{
                otherNickName = model.conversation.latestMessage.ext[@"nickName"];
                otherIcon = model.conversation.latestMessage.ext[@"icon"];
                otherIconColor = model.conversation.latestMessage.ext[@"iconColor"];
            }
            if (dict[@"soundCard"]){
                otherNickName = model.conversation.latestMessage.ext[@"nickName"];
                if ([model.conversation.conversationId isEqualToString:@"admin"]){
                    otherNickName = @"hearer君每日推荐";
                }else{
                    viewController.isSayHello = YES;
                }
            }
            viewController.otherNickNameStr = otherNickName;
            viewController.otherIconName = otherIcon;
            viewController.otherIconStr = otherIconColor;
            viewController.title = otherNickName;
            
            [self.navigationController pushViewController:viewController animated:YES];
        }
        
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kFullWidth, 10)];
    view.backgroundColor = CustomColor(240, 240, 240, 1);
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0){
        return 0;
    }else{
        return 10;
    }
}

- (void)addButtonClick:(UIButton *)button{
    
    [YBPopupMenu showRelyOnView:button titles:@[@"查找用户",@"清空消息"] icons:@[@"添加好友",@"清空消息"] menuWidth:140.f textColor:FirstTextColor delegate:self];

}

#pragma -mark- YBPopupMenuDelegate
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu *)ybPopupMenu{
    if (index == 0){
        HRSearchFirendsViewController *VC = [HRSearchFirendsViewController new];
        [self.navigationController pushViewController:VC animated:YES];
    }else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否清空当前所有聊天列表" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alertView.alertViewStyle=UIAlertViewStyleDefault;
        
        [alertView show];

    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1){
        
        [[EMClient sharedClient].chatManager deleteConversations:[[EMClient sharedClient].chatManager getAllConversations] isDeleteMessages:YES completion:^(EMError *aError){
            if (!aError){
                [self.dataArray removeAllObjects];
                [self.tableView reloadData];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTabItemBageCountNotifi" object:nil];
            }
        }];
    }
}

- (void)didReceiveMessages:(NSArray *)aMessages {
    [self tableViewDidTriggerHeaderRefresh];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTabItemBageCountNotifi" object:nil];
    [self newMessageNotifi];
    
    [self newFirendsNotifi];
    
}

-(void)newMessageNotifi{
//    self.isNewSystemMessage =  || [[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"5"]] ||[[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"2"]] ||[[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"9"]];
    
//    self.circleUnreadCount = [[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"1",@"2",@"5"]];
//    self.hearVoiceUnreadCount = [[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"9",@"12"]];
//
//    if (self.circleUnreadCount || self.hearVoiceUnreadCount){
//        [self.tableView reloadData];
//    }
    
    self.noticeUnreadCount = [[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:nil];
    if (self.noticeUnreadCount){
        [self.tableView reloadData];
    }
}

- (void)newFirendsNotifi{
    self.firendsUnreadCount = [[HRFMDBDynamicNotifacationTool sharedInstance] unReadCount:@[@"10"]];
    if (self.firendsUnreadCount){
        [self.tableView reloadData];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
